package controllerGoods

import (
	"github.com/gin-gonic/gin"
	goods_pb "mxshop/api/goods/v1"
	doGoods "mxshop/app/mxshop_api/api/internal/domain/do/goods"
	dtoGoods "mxshop/app/mxshop_api/api/internal/domain/dto/goods"
	"mxshop/gmicro/pkg/common/core"
	translatorGin "mxshop/pkg/translator/gin"
	"net/http"
	"strconv"
)

type CategoryBrandFilter struct {
	Pages       int32    `form:"p" json:"p"`
	PagePerNums int32    `form:"n" json:"n"`
	OrderBy     []string `form:"o" json:"o"`
}

func (gc *GoodsController) CategoryBrandList(ctx *gin.Context) {
	var filter CategoryBrandFilter
	if err := ctx.ShouldBindQuery(&filter); err != nil {
		translatorGin.HandleValidatorError(ctx, err, gc.trans)
		return
	}

	rsp, err := gc.srv.Goods().CategoryBrand().CategoryBrandList(ctx, &goods_pb.CategoryBrandFilterRequest{
		Pages:       filter.Pages,
		PagePerNums: filter.PagePerNums,
		Orderby:     filter.OrderBy,
	})
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}

	ctx.JSON(200, rsp)
	return
}

func (gc *GoodsController) CategoryBrandDelete(ctx *gin.Context) {
	id := ctx.Param("id")
	idInt, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}

	if err := gc.srv.Goods().CategoryBrand().DeleteCategoryBrand(ctx, idInt); err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}
	ctx.Status(http.StatusOK)
	return
}

func (gc *GoodsController) CategoryBrandNew(ctx *gin.Context) {
	var req dtoGoods.CategoryBrandDTO
	if err := ctx.ShouldBindJSON(&req); err != nil {
		translatorGin.HandleValidatorError(ctx, err, gc.trans)
		return
	}

	rsp, err := gc.srv.Goods().CategoryBrand().CreateCategoryBrand(ctx, &req)
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}

	ctx.JSON(200, gin.H{"ID": rsp.Id})
	return
}

func (gc *GoodsController) CategoryBrandUpdate(ctx *gin.Context) {
	id := ctx.Param("id")
	idInt, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}

	var req dtoGoods.CategoryBrandDTO
	if err := ctx.ShouldBindJSON(&req); err != nil {
		translatorGin.HandleValidatorError(ctx, err, gc.trans)
		return
	}

	if err := gc.srv.Goods().CategoryBrand().UpdateCategoryBrand(ctx, &dtoGoods.CategoryBrandDTO{CategoryBrandDO: doGoods.CategoryBrandDO{
		Id:         idInt,
		CategoryId: req.CategoryId,
		BrandId:    req.BrandId,
	}}); err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}
	ctx.Status(http.StatusOK)
	return
}

func (gc *GoodsController) CategoryBrandGetList(ctx *gin.Context) {
	id := ctx.Param("id")
	idInt, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}

	rsp, err := gc.srv.Goods().CategoryBrand().GetCategoryBrandList(ctx, idInt)
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}

	ctx.JSON(200, rsp)
	return
}
